﻿using NLog.Layouts;
using NLog.Targets;
using NLog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MultiCommunication.Models
{
    [Target("WpfLogTarget")]
    public sealed class WpfLogTarget : TargetWithLayout
    {
        public ObservableCollection<LogEntry> LogEntries { get; } = new ObservableCollection<LogEntry>();
        public int MaxLogCount { get; set; } = 1000;

        protected override void Write(LogEventInfo logEvent)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                LogEntries.Add(new LogEntry
                {
                    TimeStamp = logEvent.TimeStamp,
                    Level = logEvent.Level.ToString(),
                    Logger = logEvent.LoggerName,
                    Message = logEvent.FormattedMessage,
                    Exception = logEvent.Exception?.ToString()
                });

                if (LogEntries.Count > MaxLogCount)
                {
                    LogEntries.RemoveAt(0);
                }
            }));
        }
    }
}
